<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <title>扫码结果</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: "Segoe UI", Arial, sans-serif;
            margin: 0;
            padding: 16px;
            background-color: #f8f9fa;
            font-size: 16px;
        }

        h2 {
            text-align: center;
            font-size: 1.4rem;
            margin-bottom: 20px;
            color: #333;
        }

        .el-table {
            margin-bottom: 20px;
        }

        .button-container {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 20px;
        }

        .button-container .el-button {
            width: 48%;
            height: 50px;
            font-size: 1rem;
        }

        .el-dialog {
            width: 95% !important;
            margin: 10px auto !important;
            border-radius: 8px;
        }

        .el-dialog__header {
            font-size: 1.2rem !important;
        }

        .el-dialog__body {
            padding: 16px;
        }

        .el-dialog__footer {
            text-align: right;
        }

        .el-button--primary {
            width: 100%;
            font-size: 1rem;
            padding: 14px 0;
        }

        .el-form {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .el-form-item {
            width: 100%;
        }

        .el-form-item__label {
            display: block;
            margin-bottom: 6px;
            font-size: 1rem;
        }

        .el-input,
        .el-input-number,
        .el-date-editor {
            width: 100%;
        }

        .el-input input,
        .el-input-number .el-input__inner,
        .el-date-editor input {
            font-size: 1rem;
            height: 48px;
            padding: 0 12px;
            border-radius: 6px;
            width: 100%;
        }

        .dialog-actions {
            display: flex;
            justify-content: space-between;
            gap: 16px;
            margin-top: 12px;
        }

        .dialog-actions .el-button {
            flex: 1;
        }
        .device-info-box {
            background-color: #fff;
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        }

        .device-info-item {
            margin-bottom: 10px;
            font-size: 1rem;
            color: #333;
        }

    </style>
</head>
<body>
<div id="app">
    <h2>扫码结果</h2>

    <div class="device-info-box" v-if="deviceInfo.length">
        <div class="device-info-item"><strong>ID：</strong>{{ deviceInfo[0].sparepartid }}</div>
        <div class="device-info-item"><strong>型号：</strong>{{ deviceInfo[0].model }}</div>
        <div class="device-info-item"><strong>规格：</strong>{{ deviceInfo[0].specification }}</div>
        <div class="device-info-item"><strong>供应商名称：</strong>{{ deviceInfo[0].supplierName }}</div>
        <div class="device-info-item"><strong>设备类型：</strong>{{ deviceInfo[0].devicetype }}</div>
        <div class="device-info-item"><strong>重要性级别：</strong>{{ deviceInfo[0].importancelevel }}</div>
        <div class="device-info-item"><strong>总库存：</strong>{{ deviceInfo[0].totalQuantity }}</div>
        <div class="device-info-item"><strong>状态：</strong>{{ deviceInfo[0].status }}</div>
    </div>


    <div class="button-container">
        <el-button type="primary" @click="showInBoundDialog = true">入库</el-button>
        <el-button type="success" @click="showOutBoundDialog = true">出库</el-button>
    </div>

    <!-- 入库 -->
    <el-dialog v-model="showInBoundDialog" title="新增入库记录" :fullscreen="$store.getters.isMobile">
        <el-form :model="inBoundForm" label-position="top">
            <el-form-item label="备件ID">
                <el-input v-model.number="inBoundForm.sparepartid" disabled></el-input>
            </el-form-item>
            <el-form-item label="数量">
                <el-input-number v-model.number="inBoundForm.quantity" :min="1" @change="calculateTotalPrice"></el-input-number>
            </el-form-item>
            <el-form-item label="单价">
                <el-input-number v-model.number="inBoundForm.unitPrice" :step="0.01" :min="0" @change="calculateTotalPrice"></el-input-number>
            </el-form-item>
            <el-form-item label="总价">
                <el-input v-model.number="inBoundForm.totalPrice" disabled></el-input>
            </el-form-item>
            <el-form-item label="批次号">
                <el-input v-model="inBoundForm.batchNumber"></el-input>
            </el-form-item>
            <el-form-item label="日期">
                <el-date-picker v-model="inBoundForm.date" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <div class="dialog-actions">
                <el-button @click="showInBoundDialog = false">取消</el-button>
                <el-button type="primary" @click="submitInBound">提交</el-button>
            </div>
        </el-form>
    </el-dialog>

    <!-- 出库 -->
    <el-dialog v-model="showOutBoundDialog" title="新增出库记录" :fullscreen="$store.getters.isMobile">
        <el-form :model="outBoundForm" label-position="top">
            <el-form-item label="备件ID">
                <el-input v-model.number="outBoundForm.sparepartid" disabled></el-input>
            </el-form-item>
            <el-form-item label="数量">
                <el-input v-model.number="outBoundForm.quantity"></el-input>
            </el-form-item>
            <el-form-item label="批次号">
                <el-input v-model="outBoundForm.batchNumber"></el-input>
            </el-form-item>
            <el-form-item label="日期">
                <el-date-picker v-model="outBoundForm.date" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <div class="dialog-actions">
                <el-button @click="showOutBoundDialog = false">取消</el-button>
                <el-button type="primary" @click="submitOutBound">提交</el-button>
            </div>
        </el-form>
    </el-dialog>
</div>

<script src="https://unpkg.com/vue@3.2.36/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-plus"></script>

<script>
    const { createApp } = Vue;

    function isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    const apiClient = axios.create({
        //本机地址
        //baseURL: 'http://localhost:8086',
        //服务器 地址
        baseURL: 'http://8.137.85.243:8086',
        timeout: 5000
    });

    const app = createApp({
        data() {
            return {
                deviceInfo: [],
                showInBoundDialog: false,
                inBoundForm: {
                    sparepartid: null,
                    quantity: 1,
                    unitPrice: 0.0,
                    totalPrice: 0.0,
                    batchNumber: '',
                    date: new Date().toISOString().split('T')[0],
                    userid: 1
                },
                showOutBoundDialog: false,
                outBoundForm: {
                    sparepartid: null,
                    quantity: null,
                    batchNumber: '',
                    date: null,
                    userid: 1
                }
            };
        },
        mounted() {
            this.loadData();
        },
        methods: {
            calculateTotalPrice() {
                if (this.inBoundForm.quantity && this.inBoundForm.unitPrice) {
                    this.inBoundForm.totalPrice = (this.inBoundForm.quantity * this.inBoundForm.unitPrice).toFixed(2);
                } else {
                    this.inBoundForm.totalPrice = 0.0;
                }
            },
            async loadData() {
                const urlParams = new URLSearchParams(window.location.search);
                const result = urlParams.get('result');

                if (result) {
                    this.inBoundForm.sparepartid = Number(result);
                    this.outBoundForm.sparepartid = Number(result);

                    try {
                        const res = await apiClient.get(`/api/spareparts/findbyid/${result}`);
                        const data = res.data;

                        const categoryRes = await apiClient.get(`/api/sparecategories/findbysparepartid/${result}`);
                        const supplierRes = await apiClient.get(`/api/suppliers/findbyid/${data.supplierid}`);
                        const inventoryRes = await apiClient.get(`/api/inventoryalerts/findbysparepartid/${result}`);

                        const inventoryData = inventoryRes.data[0] || {};
                        const categoryData = categoryRes.data[0] || {};
                        const supplierData = supplierRes.data || {};

                        this.deviceInfo = [{
                            sparepartid: data.sparepartid,
                            model: data.model,
                            specification: data.specification,
                            supplierName: supplierData.name || '未知供应商',
                            devicetype: categoryData.devicetype || '未知',
                            importancelevel: categoryData.importancelevel || '未知',
                            totalQuantity: inventoryData.totalQuantity || 0,
                            status: inventoryData.status || '正常'
                        }];
                    } catch (err) {
                        console.error("获取数据失败:", err);
                        alert("无法加载备件信息");
                    }
                }
            },
            async submitInBound() {
                if (!this.inBoundForm.quantity || !this.inBoundForm.unitPrice || !this.inBoundForm.batchNumber || !this.inBoundForm.date) {
                    alert('请填写完整信息（数量、单价、批次号、日期）');
                    return;
                }

                try {
                    await apiClient.post('/api/inboundrecords/insert', {
                        sparepartid: this.inBoundForm.sparepartid,
                        quantity: this.inBoundForm.quantity,
                        batchNumber: this.inBoundForm.batchNumber,
                        date: this.inBoundForm.date,
                        userid: this.inBoundForm.userid
                    });

                    await apiClient.post('/api/batchmanagement/insert', {
                        sparepartid: this.inBoundForm.sparepartid,
                        quantity: this.inBoundForm.quantity,
                        batchNumber: this.inBoundForm.batchNumber,
                        entryDate: this.inBoundForm.date,
                        unitPrice: parseFloat(this.inBoundForm.unitPrice),
                        totalPrice: parseFloat(this.inBoundForm.totalPrice)
                    });

                    this.showInBoundDialog = false;
                    alert("入库成功");
                } catch (error) {
                    alert("入库失败：" + error.message);
                    console.error("入库失败:", error);
                }
            },
            async submitOutBound() {
                if (!this.outBoundForm.quantity || !this.outBoundForm.batchNumber || !this.outBoundForm.date) {
                    alert('请填写完整信息（数量、批次号、日期）');
                    return;
                }

                try {
                    await apiClient.post('/api/outboundrecords/insert', this.outBoundForm);
                    this.showOutBoundDialog = false;
                    alert("出库成功");
                } catch (error) {
                    alert("出库失败：" + error.message);
                }
            }
        }
    });

    app.use(ElementPlus);

    app.config.globalProperties.$store = {
        getters: {
            isMobile: isMobileDevice()
        }
    };

    app.mount('#app');
</script>
</body>
</html>
